package org.activiti.designer.test;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;
import java.io.FileInputStream;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.ActivitiRule;
import org.junit.Rule;
import org.junit.Test;

public class ProcessTestUserAndGroupInUserTask {

	private String filename = "/Users/haoxiaoliang/work/workspace-tools/bpmn20-example/src/main/resources/diagrams/userAndGroupInUserTask.bpmn";

	@Rule
	public ActivitiRule activitiRule = new ActivitiRule();

	@Test
	public void startProcess() throws Exception {
		//创建用户和组，并关联
		IdentityService identityService = activitiRule.getIdentityService();
		Group group = identityService.newGroup("deptLeader");
		group.setName("部门领导");
		group.setType("assignment");
		identityService.saveGroup(group);
		//添加第一个用户
		User user = identityService.newUser("wayne");
		user.setFirstName("wayne");
		user.setLastName("rooney");
		user.setEmail("wayne@rooney.com");
		identityService.saveUser(user);
		identityService.createMembership("wayne", "deptLeader");
		//添加第二个用户
		user = identityService.newUser("lilei");
		user.setFirstName("li");
		user.setLastName("lei");
		user.setEmail("li@lei.com");
		identityService.saveUser(user);
		identityService.createMembership("lilei", "deptLeader");
		
		
		
		
		RepositoryService repositoryService = activitiRule.getRepositoryService();
		repositoryService.createDeployment().addInputStream("userAndGroupInUserTask.bpmn20.xml",
				new FileInputStream(filename)).deploy();
		RuntimeService runtimeService = activitiRule.getRuntimeService();
		Map<String, Object> variableMap = new HashMap<String, Object>();
		variableMap.put("name", "Activiti");
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("userAndGroupInUserTask", variableMap);
		assertNotNull(processInstance.getId());
		System.out.println("id " + processInstance.getId() + " "
				+ processInstance.getProcessDefinitionId());
		//流程启动后查询两个组用户是否都有待处理的任务
		TaskService taskService = activitiRule.getTaskService();
		Task wayneTask = taskService.createTaskQuery().taskCandidateUser("wayne").singleResult();
		assertNotNull(wayneTask);
		Task lileiTask = taskService.createTaskQuery().taskCandidateUser("lilei").singleResult();
		assertNotNull(lileiTask);
		//其中一人签收后，查看另一个人是否还能查询到待处理的任务
		taskService.claim(wayneTask.getId(), "wayne");
		
		lileiTask = taskService.createTaskQuery().taskCandidateUser("lilei").singleResult();
		assertNull(lileiTask);
		
		taskService.complete(wayneTask.getId());
		
		
		
		
	}
	
	
	
	
}